<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
	<meta charset="UTF-8">
    <title>出库申请登记</title>
    <link rel="stylesheet"  href="/bootstrap/bootstrap-5.3.3-dist/css/bootstrap.min.css" />
   	<link rel="stylesheet" href="/css/stock/c/Warehousing_Application_Registration.css" />
   <style type="text/css">
    	
    </style>
</head>
<body style="padding: 15px 50px;background-color: #eeeeee;">
	<div class="panel-heading hhead">
		<nav aria-label="breadcrumb">
		  <ol class="breadcrumb">
		  	<span style="color: blue;">您正在做的业务是：</span>
		    <li class="breadcrumb-item"><a href="#">库存管理</a></li>
		    <li class="breadcrumb-item"><a href="#">出库申请管理</a></li>
		    <li class="breadcrumb-item active" aria-current="page">出库申请登记</li>
		  </ol>
		</nav>
	</div>
	<form id="searchForm">
		<input type="hidden" id="page" name="pageNum" value="1">
		<input type="hidden" id="pageSize" name="pageSize" value="5">
		<input type="hidden" name="checkTag" value="1">
		<input type="hidden" name="designModuleTag" value="0">
		<input type="hidden" name="firstId" value="0">
		<input type="hidden" name="secondId" value="0">
		<input type="hidden" name="thirdId" value="0">
		<input type="hidden" name="startDate" value="">
		<input type="hidden" name="endDate" value="">
	</form>
    <div style="margin-bottom: 2px">
        <div style="display: inline;margin-left: 72%;">
            <button class="btn btn-primary" id="btnAdd" data-bs-toggle="modal" data-bs-target="#proRegistraModal">添加产品</button>
            <button class="btn btn-primary" id="delete">删除产品</button>
            <button class="btn btn-primary" id="search">预览</button>
            <button class="btn btn-primary">返回</button>
        </div>
    </div> <!-- 此div改用栅格来做 -->
    <div id="designListBox">
        <div style="text-align: center">
            <h3>出库申请单</h3>
        </div>
        <div style="padding: 30px">
           <table class="tbl1">
               <tr>
                   <td class="col1">出库人：</td>
                   <td class="col2" id="outbound">${user.loginId}</td>
                   <td class="col1">出库理由：</td>
                   <td class="col2">
                   	<select id="reason">
                   		<option value="赠送">赠送</option>
						<option value="内部借领">内部借领</option>
						<option value="其他借领">其他借领</option>
                   	</select>
                   </td>
               </tr>

           </table>

            <table class="table table-bordered" style="margin: 15px auto;">
                <thead>
                    <tr>
                        <th>点选</th><th>产品名称</th><th>产品编号</th>
                        <th>描述</th><th>数量</th><th>单位</th>
                        <th>成本单价（元）</th><th>小计（元）</th>
                    </tr>
                </thead>
                <tbody id="template">

                </tbody>

            </table>

            <table class="tbl3">
            	<tr>
                    <td class="col1">总件数：</td>
                    <td class="col2" id="totalNum"></td>
                    <td class="col1">总金额：</td> <td class="col2" id="totalPrice"></td>
                </tr>
                <tr>
                    <td class="col1">登记人：</td>
                    <td class="col2"><input type="text" class="txt_under_line"  id="Registrants"></td>
                    <td class="col1">登记时间：</td> <td class="col2"  id="time">系统时间</td>
                </tr>
                <tr>
                    <td class="col1">备注：</td>
                    <td colspan="3" style="padding-top: 5px">
                        <textarea rows="4" cols="100" id="remark"></textarea>
                    </td>
                </tr>
            </table>
        </div>
    </div>
    
    <div class="modal fade" id="proRegistraModal" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
			<div class="modal-dialog modal-xl">
					<div class="modal-content">
						<div class="modal-header">
							<h2>添加产品</h2>
							<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
						</div>
						<div class="modal-body">
							<div class="container-fluid">
								<div id="bodyBox">
									<form>
										<div class="panel product">
											<div class="panel-heading hhead">
												<nav aria-label="breadcrumb">
												  <ol class="breadcrumb">
												  	<span style="color: blue;">您正在做的业务是：</span>
												    <li class="breadcrumb-item"><a href="#">库存管理</a></li>
												    <li class="breadcrumb-item"><a href="#">出库申请管理</a></li>
												    <li class="breadcrumb-item active" aria-current="page">出库申请登记</li>
												  </ol>
												</nav>

												<div>
													<p><small>符合条件的产品档案总数：<span style="color: red;" id="num">2</span>例</small></p>
												</div>
											</div>
											
											<div class="panel-body bbody">
												<table id="tab" >
													<thead>
														<tr style="background-color: #e8e8e8;">
															<td>产品编号</td>
															<td>产品名称</td>
															<td>用途类型</td>
															<td>单位</td>
															<td>成本单价</td>
															<td>出库</td>
														</tr>
													</thead>
													<tbody id="template2">
<%--														<tr>--%>
<%--															<td>aaaaaa</td>--%>
<%--															<td>bbbb</td>--%>
<%--															<td>ccc</td>--%>
<%--															<td>ddd</td>--%>
<%--															<td>fff</td>--%>
<%--															<td><a href="">出库</a></td>--%>
<%--														</tr>--%>
													</tbody>
												</table>
											</div>
											
											<div class="panel-footer ffooter">
												<div id="footerDiv">
													<label style="font-weight: 700;">总数：<span style="color: red;" id="footNum1">5</span>例&nbsp;&nbsp;&nbsp;&nbsp;
														当前第<span style="color: red;" id="pageNum1">1</span>页&nbsp;&nbsp;&nbsp;&nbsp;
														共<span style="color: red;" id="pagesNum1">1</span>页&nbsp;&nbsp;&nbsp;&nbsp;
													</label>
												</div>
											</div>
										</div>
									</form>
								</div>
							</div>
						</div>
						<div class="modal-footer">
							<button id="btnConcel" class="btn btn-danger" data-bs-dismiss="modal">
								关闭<span class="glyphicon glyphicon-remove"></span>
							</button>
						</div>
					</div>
				</div>
		</div>
		
		<script type="text/javascript" src="/js/jquery-3.7.0.min.js"></script>
		<script type="text/javascript" src="/bootstrap/bootstrap-5.3.3-dist/js/bootstrap.bundle.min.js"></script>
		<script type="text/javascript" src="/js/common.js"></script>
		<script type="text/javascript">
			$(function(){
				// 初始化数据
				initData();
				// 初始化事件
				initEvent();

				// 初始化模态框中的表格
				initialArchiveTable(1);

				$("#AddModuleDetailsModal").on("hidden.bs.modal", function () {
					// $("#iframe2").attr("src", "");
					let IdItems = sessionStorage.getItem("IdItems");
					console.log(IdItems)
					sessionStorage.clear();
					IdItems = JSON.parse(IdItems);
					$("#template").empty();
					for (let i = 0; i < IdItems.length; i++) {
						let id = IdItems[i];
						addToTable(id);
					}
				})

				// 取消按钮
				$("#btnConcel").click(function () {
					$("#proRegistraModal").modal("hide");
				})

				$("#proRegistraModal").on("hidden.bs.modal", function () {
					if (sessionStorage.length > 0) {
						let IdItems = sessionStorage.getItem("IdItems");
						console.log(IdItems)
						sessionStorage.clear();
						IdItems = JSON.parse(IdItems);
						if(IdItems==null){
							return;
						}
						$("#template").empty();
						for (let i = 0; i < IdItems.length; i++) {
							let id = IdItems[i];
							addToTable(id);
						}
					}
				});

				$("#delete").click(function () {
					let rows = $("#template tr");

					let totalNum=0;
					let totalPrice=0;
					console.log(rows)
					for (let i = 0; i < rows.length; i++) {
						let row = rows[i];
						let checkbox = $(row).find("input[type='checkbox']");

						if (checkbox.prop("checked")) {
							$(row).remove();
						}else{
							let num = $(row).find("td:eq(4) input").val();
							let unitPrice = $(row).find("td:eq(7)").text();
							if(unitPrice!=""){
								totalPrice+=parseInt(unitPrice);
							}
							if(num!=""){
								totalNum+=parseInt(num);
							}
						}

					}
					$("#totalNum").text(totalNum);
					$("#totalPrice").text(totalPrice);
				})

				$("#search").click(function () {
					//获取出库人
					let outbound = $("#outbound").text();
					if($("#Registrants").val() == ""){
						$("#Registrants").text(outbound);
					}
					if($("#template tr").length==0){
						alert("请添加产品(至少一种)");
						return;
					}
					//获取出库理由
					let reason=$("#reason option:selected").val();
					// // 获取产品id
					// let productId = $("#productId").text();
					// // 获取产品名称
					// let productName = $("#productName").text();

					//获取总件数
					let totalNum = $("#totalNum").text();
					//获取总金额
					let totalPrice = $("#totalPrice").text();

					//登记人
					let register = $("#Registrants").val();
					//登记时间
					let registerTime = $("#time").text();
					//备注
					let remark = $("#remark").val();

					let rows = $("#template tr");
					let data = [];
					data.push({
						outbound:outbound,
						reason: reason,
						totalNum:totalNum,
						totalPrice: totalPrice,
						registerTime: registerTime,
						register: register,
						remark: remark
					})
					for (let i = 0; i < rows.length; i++) {
						let row = rows[i];
						let productId = $(row).find("td:eq(2)").text();
						let productName = $(row).find("td:eq(1)").text();
						let productDescribe=$(row).find("td:eq(3)").text();
						let num = $(row).find(".num-input").val();
						if(num==""){
							alert("请输入编号为"+id+"的数量,才能预览");
							return;
						}

						let amountUnit = $(row).find("td:eq(5)").text();
						let costPrice = $(row).find("td:eq(6)").text();
						//小计
						let total = $(row).find("td:eq(7)").text();
						let obj = {
							productId: productId,
							productName: productName,
							productDescribe:productDescribe,
							num: num,
							amountUnit: amountUnit,
							costPrice: costPrice,
							total: total
						}
						data.push(obj);
					}
					console.log(data)
					sessionStorage.setItem("data", JSON.stringify(data));
					alert("提交成功");
					window.location.href="/s-pay/WarehouseOutApplicationRegistrationPreview";
				})
				$("#template").on("input",".num-input", function () {
					let num = $(this).val();
					let row = $(this).parent().parent();
					let costPrice = $(row).find("td:eq(6)").text();
					let total = costPrice * num;
					$(row).find("td:eq(7)").text(total);

					let totalNum=0;
					let totalPrice=0;
					let rows = $("#template tr");
					console.log(rows)
					for (let i = 0; i < rows.length; i++) {
						let row = rows[i];
						let num = $(row).find("td:eq(4) input").val();
						let unitPrice = $(row).find("td:eq(7)").text();
						if(unitPrice!=""){
							totalPrice+=parseInt(unitPrice);
						}
						if(num!=""){
							totalNum+=parseInt(num);
						}

					}
					$("#totalNum").text(totalNum);
					$("#totalPrice").text(totalPrice);
				})
				// 初始化时间
				setInterval(updateDateTime, 1000);
			})

			function Add(id) {
				let IdItems = [];
				if(sessionStorage.getItem("IdItems") != null){
					IdItems = JSON.parse(sessionStorage.getItem("IdItems"));
				}
				if(IdItems.indexOf(id) != -1){
					alert("该物料已添加");
					return;
				}
				IdItems.push(id);
				sessionStorage.getItem("IdItems") == null? sessionStorage.setItem("IdItems",JSON.stringify(IdItems)) : sessionStorage.setItem("IdItems",JSON.stringify(IdItems));
			}

			function updateDateTime(){
				let date = new Date();
				let year = date.getFullYear();
				let month = (date.getMonth() + 1).toString().padStart(2, '0');
				let day = date.getDate().toString().padStart(2,'0');
				let hours = date.getHours().toString().padStart(2,'0');
				let minutes = date.getMinutes().toString().padStart(2,'0');
				let seconds = date.getSeconds().toString().padStart(2,'0');
				let dateTimeStr = year+"-"+month+"-"+day+" "+hours+":"+minutes+":"+seconds;
				$("#time").text(dateTimeStr);
			}

			function addToTable(id){
				$.ajax({
					url: "/d-module/getMaterialById?id=" + id,
					type: "get",
					datatype: "json",
					success: function (data) {
						console.log(data)
						let row = "<tr>" +
								"<td class='ckbox'><input type='checkbox' /></td>" +
								"<td>" + data.productName  + "</td>" +
								"<td>" + data.productId + "</td>" +
								"<td>" + data.productDescribe + "</td>" +
								"<td class='num'>" +
								"<input class='num-input' value=''></td>" +
								"<td>" + data.amountUnit+ "</td>" +
								"<td>" + data.costPrice + "</td>" +
								"<td>" +""+ "</td>" +
								"</tr>";
						$("#template").append(row);
					}
				})
			}

			//初始化模态框中的表格
			function initialArchiveTable(pageNum) {
				$("#page").val(pageNum)
				let json = formDateToJson("searchForm");
				$.ajax({
					url: "/d-file/initialArchiveTable",
					type: "POST",
					data: json,
					contentType: "application/json",
					dataType: "json",
					success: function (Page) {
						console.log(Page)
						$("#num").html(Page.total);
						$("#footNum1").html(Page.total);
						$("#pageNum1").html(pageNum);
						let pages = Math.ceil(Page.total / 5);
						$("#pagesNum1").html(pages);
						params = {
							"First": 1,
							"Previous": Page.current > 1 ? Page.current - 1 : 1,
							"Next": Page.current < pages ? Page.current + 1 : pages,
							"Last": pages
						};
						console.log(params);

						$("#a0").attr("href", "javascript:initialArchiveTable(" + params.First + ")")
						if(pageNum <= 2){
							a1 = 1;
							a2 = 2;
							a3 = 3;
						}else if(pageNum >= pages - 1){
							a1 = pages - 2;
							a2 = pages - 1;
							a3 = pages;
						}else {
							a1 = pageNum - 1;
							a2 = pageNum;
							a3 = pageNum + 1;
						}
						$("#a1").attr("href", "javascript:initialArchiveTable(" + a1 + ")")
						$("#a1").html(a1)
						a1 == pageNum? $("#a1").addClass("active") : $("#a1").removeClass("active")
						$("#a2").attr("href", "javascript:initialArchiveTable(" + a2 + ")")
						$("#a2").html(a2)
						a2 == pageNum? $("#a2").addClass("active") : $("#a2").removeClass("active")
						a3 == pageNum? $("#a3").addClass("active") : $("#a3").removeClass("active")
						$("#a3").attr("href", "javascript:initialArchiveTable(" + a3 + ")")
						$("#a3").html(a3)
						$("#a4").attr("href", "javascript:initialArchiveTable(" + params.Last + ")")
						tbody = $("#template2");
						tbody.empty();

						var files = Page.list;
						FileArr = ["productId", "productName","type","amountUnit","costPrice", "formulate"]
						for (var i = 0; i < files.length; i++) {
							var tr = document.createElement("tr");
							var product = files[i];
							for (var k in FileArr) {
								var td = document.createElement("td");
								console.log(product[FileArr[k]])
								if (FileArr[k] == "type") {
									td.innerHTML = product[FileArr[k]] != undefined ? product.dproductUse.useName : "";
									tr.appendChild(td);
								}else if(FileArr[k] == "formulate"){
									let b = "<a href='javascript:Add("  + files[i]["id"]+ ")' class='btn btn-outline-success ' >出库</a>";
									td.innerHTML = b;
									tr.appendChild(td);
								}else {
									td.innerHTML = product[FileArr[k]] != undefined ? product[FileArr[k]] : "";
									tr.appendChild(td);
								}
							}
							tbody[0].appendChild(tr);
						}
						sessionStorage.clear();
					},
					error: function (e) {

					}
				})
			}

			// 初始化数据
			function initData() {
				// 初始化一级分类
				initialFirstLevel();
			}
			// 初始化事件
			function initEvent() {
				// 一级分类选择事件
				$('#firstLevel').on('change', function () {
					let firstId = $(this).val();
					if (firstId == '') {
						$('#secondLevel option:gt(0)').remove();
						$('#thirdLevel option:gt(0)').remove();
						return;
					}
					// 存储一级分类名称
					$('#firstKindName').val($(this).find('option:selected').text());
					// 初始化二级分类
					initialSecondLevel(firstId);
				});
				// 二级分类选择事件
				$('#secondLevel').on('change', function () {
					let secondId = $(this).val();
					if (secondId == '') {
						$('#thirdLevel option:gt(0)').remove();
						return;
					}
					// 存储二级分类名称
					$('#secondKindName').val($(this).find('option:selected').text());
					// 存储二级分类名称
					initialThirdLevel(secondId);
				});
				// 三级分类选择事件
				$('#thirdLevel').on('change', function () {
					let thirdId = $(this).val();
					if (thirdId == '') {
						return;
					}
					// 存储三级分类名称
					$('#thirdKindName').val($(this).find('option:selected').text());
				});

				$('#state').on('click', function (){
					window.location.href= "/s-cell/Formulat_safety_stock";
				})


			}
			function initialFirstLevel() {
				$.ajax({
					url: "/d-level-first/initialLevel",
					type: "get",
					dataType: "json",
					success: function (data) {
						console.log(data);
						let firstLevel = $('#firstLevel');
						$('#firstLevel option:gt(0)').remove();
						$('#secondLevel option:gt(0)').remove();
						$('#thirdLevel option:gt(0)').remove();
						for (let i = 0; i < data.length; i++) {
							let option = $('<option>');
							option.val(data[i].firstId);
							option.text(data[i].firstName);
							firstLevel.append(option);
						}
					}
				})
			}
			function initialSecondLevel(firstId) {
				$.ajax({
					url: "/d-level-second/initialLevel?firstId="+firstId,
					type: "get",
					dataType: "json",
					success: function (data) {
						console.log(data);
						let secondLevel = $('#secondLevel');
						$('#secondLevel option:gt(0)').remove();
						$('#thirdLevel option:gt(0)').remove();
						for (let i = 0; i < data.length; i++) {
							let option = $('<option>');
							option.val(data[i].secondId);
							option.text(data[i].secondName);
							secondLevel.append(option);
						}
					}
				})
			}
			function initialThirdLevel(secondId) {
				$.ajax({
					url: "/d-level-third/initialLevel?secondId="+secondId,
					type: "get",
					dataType: "json",
					success: function (data) {
						console.log(data);
						let thirdLevel = $('#thirdLevel');
						$('#thirdLevel option:gt(0)').remove();
						for (let i = 0; i < data.length; i++) {
							let option = $('<option>');
							option.val(data[i].thirdId);
							option.text(data[i].thirdName);
							thirdLevel.append(option);
						}
					}
				})
			}
			function Add(id) {
				let IdItems = [];
				if(sessionStorage.getItem("IdItems") != null){
					IdItems = JSON.parse(sessionStorage.getItem("IdItems"));
				}
				if(IdItems.indexOf(id) != -1){
					alert("该产品已添加");
					return;
				}
				IdItems.push(id);
				sessionStorage.getItem("IdItems") == null? sessionStorage.setItem("IdItems",JSON.stringify(IdItems)) : sessionStorage.setItem("IdItems",JSON.stringify(IdItems));
			}
		</script>
</body>
</html>
